#!/usr/bin/python
# -*- coding: utf-8 -*-

import imgword_spilter
from multiprocessing import Process,Queue

import cv2
import numpy as np


import tornado
import tornado.ioloop
import tornado.web
from tornado.escape import json_encode
import base64
import cnn_ascll_he




data_input_queue = Queue()
data_output_queue = Queue()


class Handler(tornado.web.RequestHandler):

    def post(self):
        result = {}
        imagebase64 = self.get_argument("image", default="")
        #print image_url
        imghex = base64.b64decode(imagebase64)

        img_nparray = np.asarray(bytearray(imghex), dtype=np.uint8)
        img = cv2.imdecode(img_nparray, 0)
        #保存，方便调试
        cv2.imwrite('tmp.png',img)

        #TODO 后期的分割算法就在这里调用，其实也可以考虑使用另一个线程来解决问题，也可以在算法内部使用多进程来提高效率
        imgset = imgword_spilter.spliter_word(img, 5, 0.5)

        ######################存单个图片文件到磁盘中，然后传递文件名列表给tensor引擎识别######################
        index = 1
        namelist = []
        for img in imgset:

            filename = './tmp/%d.png'%index
            #print filename
            namelist.append(filename)
            cv2.imwrite(filename, img)
            index += 1

        #放入tensor中
        data_input_queue.put(namelist)

        #获取tensorflow的结果
        words = data_output_queue.get()

        print ('get tensorflow result!!!')

        #http请求返回
        if not imagebase64:
            result["errcode"] = 404
            result["msg"] = "no image url"
        else:
            result["errcode"] = 200
            result["msg"] = words
        self.write(json_encode(result))


class ImageServer(object):

    def __init__(self, port):
        self.port = port

    def process(self):
        app = tornado.web.Application([(r"/ocr?", Handler)] )
        app.listen(self.port)

        #启动一个进程来启动 tensorflow 引擎
        p = Process(target=cnn_ascll_he.start, args=(data_input_queue,data_output_queue))
        p.start()

        #启动http server
        tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    server_port = "12381"
    server = ImageServer(server_port)
    print ("begin server at port %s ..." % server_port)
    server.process()
